package com.chookss.home.publish;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.sdk.android.vod.upload.VODSVideoUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClient;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.SvideoInfo;
import com.alibaba.sdk.android.vod.upload.session.VodHttpClientConfig;
import com.alibaba.sdk.android.vod.upload.session.VodSessionCreateInfo;
import com.chookss.BuildConfig;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.Token;
import com.chookss.home.entity.UploadEntity;
import com.chookss.mine.personal.upload.MyUploadRecordActivity;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lzy.okgo.model.Response;
import com.vincent.videocompressor.VideoCompress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class UploadVedioService extends Service {
    //    private VODUploadClient uploader;
    private String secretToken;
    private String expireTime = "60000";
    private VODSVideoUploadClient vodsVideoUploadClient;
    public static int NotificationId = 3;
    private VodHttpClientConfig vodHttpClientConfig;
    private UploadEntity uploadEntity;
    private boolean stopUpload = false;//默认正常上传  当true时切换账号中止上传
    private boolean isCompress = false;//是否压缩过
    private String compressFileUrl;  //压缩后的文件地址
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化短视频上传对象
        vodsVideoUploadClient = new VODSVideoUploadClientImpl(this.getApplicationContext());
        vodsVideoUploadClient.init();
        //构建上传参数
//参数请确保存在，如不存在SDK内部将会直接将错误throw Exception
//文件路径保证存在之外因为Android 6.0之后需要动态获取权限，请开发者自行实现获取"文件读写权限"
        vodHttpClientConfig = new VodHttpClientConfig.Builder()
                .setMaxRetryCount(2)//重试次数
                .setConnectionTimeout(15 * 1000)//连接超时
                .setSocketTimeout(15 * 1000)//socket超时
                .build();
        secretToken = Token.INSTANCE.getToken();
        initNotification();
        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        uploadEntity = (UploadEntity) intent.getSerializableExtra("data");
        compressVideo();
        return super.onStartCommand(intent, flags, startId);
    }

    private void compressVideo() {
        //压缩代码放后台执行
        String fileUrl=uploadEntity.getVideo().getFileUrl();
        String vedioType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1, fileUrl.length());
        compressFileUrl = getExternalFilesDir(Urls.UPLOADVIDEO).getAbsolutePath() + File.separator + System.currentTimeMillis() + "." + vedioType;
        Uri vedioUri = null;
        File vedio = new File(fileUrl);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            vedioUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", vedio);
        } else {
            vedioUri = Uri.fromFile(vedio);
        }
        int level = 3;
        int size = FileUtilss.getFileSize(vedio);
        int time = FileUtilss.getVideoTime(this, vedioUri);
        if (size <= 51200) {
            uploadEntity.getVideo().setVideocompress(fileUrl);
            upload();
        } else {
            if (time <= 30) {
                uploadEntity.getVideo().setVideocompress(fileUrl);
                upload();
            } else {
                float compare = size / time;
                if (compare <= 2500) {
                    level = 2;
                } else {
                    level = 3;
                }
                VideoCompress.compressVideo(fileUrl, compressFileUrl, level, new VideoCompress.CompressListener() {
                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onSuccess() {
                        //压缩成功则开始上传视频
                        isCompress = true;
                        uploadEntity.getVideo().setVideocompress(compressFileUrl);
                        upload();
                    }

                    @Override
                    public void onFail() {
                        EventBus.getDefault().post(new MyEvent("Stop_File_Upload"));
                        stopSelf();
                        MyToast.show("视频发布失败，请稍后重试");
                    }

                    @Override
                    public void onProgress(float percent) {
                        int progress = (int) (percent)/2;
                        Message msg = handler.obtainMessage();
                        msg.arg1 = progress;
                        handler.sendMessage(msg);
                    }
                });
            }
        }
    }

    private void upload() {
        //构建短视频VideoInfo，常见的描述、标题、详情都可以设置
        SvideoInfo svideoInfo = new SvideoInfo();
        svideoInfo.setTitle(uploadEntity.getVideo().getVideoTitle());//标题
        svideoInfo.setDesc("");//文件详情
        svideoInfo.setCateId(1);//分类ID
        //构建点播上传参数（重要）
        VodSessionCreateInfo vodSessionCreateInfo = new VodSessionCreateInfo.Builder()
                .setImagePath(uploadEntity.getVideo().getVideoCoverPath())//图片地址
                .setVideoPath(uploadEntity.getVideo().getVideocompress())//视频地址
                .setAccessKeyId(MyApp.accessKeyId)//临时accessKeyId
                .setAccessKeySecret(MyApp.accessKeySecret)//临时accessKeySecret
                .setSecurityToken(secretToken)//securityToken
                .setExpriedTime(expireTime)//STStoken过期时间
//                .setRequestID(requestId)//requestID，开发者可以传将获取STS返回的requestID设置也可以不设
                .setIsTranscode(true)//是否转码，如开启转码请AppSever务必监听服务端转码成功的通知
                .setSvideoInfo(svideoInfo)//短视频信息
                .setVodHttpClientConfig(vodHttpClientConfig)//网络参数
                .build();
        vodsVideoUploadClient.uploadWithVideoAndImg(vodSessionCreateInfo, new VODSVideoUploadCallback() {
            @Override
            public void onUploadSucceed(String videoId, String imageUrl) {
                //上传成功返回视频ID和图片URL
                KLog.i("jaa", "onUploadSucceed" + "videoId:" + videoId + "imageUrl" + imageUrl);
                Message msg = handler.obtainMessage();
                msg.arg1 = 100;
                handler.sendMessage(msg);
                uploadData(videoId);
            }

            @Override
            public void onUploadFailed(String code, String message) {
                //上传失败返回错误码和message，错误码有详细的错误信息请开发者仔细阅读
                KLog.i("jaa", "onUploadFailed" + "code" + code + "message" + message);
                EventBus.getDefault().post(new MyEvent("Stop_File_Upload"));
                stopSelf();
                MyToast.show("视频发布失败，请稍后重试");
            }

            @Override
            public void onUploadProgress(long uploadedSize, long totalSize) {
                //上传的进度回调，非UI线程、
                if (stopUpload) {
                    stopSelf();
                    return;
                } else {
                    int progress = (int) (uploadedSize * 100 / totalSize);
                    KLog.i("jaa", "onUploadProgress" + progress + "%");
                    Message msg = handler.obtainMessage();
                    if(isCompress){
                        //压缩过视频
                        msg.arg1 = progress/2+50;
                    }else{
                        msg.arg1 = progress;
                    }
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onSTSTokenExpried() {
                KLog.i("jaa", "onSTSTokenExpried");
                //STS token过期之后刷新STStoken，如正在上传将会断点续传
//                vodsVideoUploadClient.refreshSTSToken(accessKeyId,accessKeySecret,secretToken,expireTime);
            }

            @Override
            public void onUploadRetry(String code, String message) {
                //上传重试的提醒
                KLog.i("jaa", "onUploadRetry" + "code" + code + "message" + message);
            }

            @Override
            public void onUploadRetryResume() {
                //上传重试成功的回调，告知用户重试成功
                KLog.i("jaa", "onUploadRetryResume");
            }
        });

    }

    private void uploadData(String videoId) {
        Map<String, String> map = new HashMap<>();
        map.put("videoTitle", uploadEntity.getVideo().getVideoTitle());
        map.put("videoId", videoId);
        map.put("videoKeyWord", uploadEntity.getVideo().getVideoKeyWord());
        map.put("videoCoverPath", uploadEntity.getVideo().getVideoCoverPath());
        map.put("videoCollectionsCode", uploadEntity.getVideo().getVideoCollectionsCode());
        map.put("videoCollectionsName", uploadEntity.getVideo().getVideoCollectionsName());
        map.put("videoOpenStatus", uploadEntity.getVideo().getVideoOpenStatus());
        map.put("original", uploadEntity.getVideo().getOriginal());
        map.put("videoAuditStatus", "0");
        map.put("catalogCodes", uploadEntity.getVideo().getCatalogCodes());
        map.put("videoLocation", uploadEntity.getVideo().getVideoLocation());
        map.put("shareFlag", uploadEntity.getVideo().getShareFlag());
        String url = "";
        if (Utils.isNull(uploadEntity.getVideo().getId())) {
            url = Urls.addVideo;
        } else {
            map.put("id", uploadEntity.getVideo().getId());
            map.put("provideEmployeeCode", uploadEntity.getVideo().getProvideEmployeeCode());
            map.put("provideEmployeename", uploadEntity.getVideo().getProvideEmployeeName());
            url = Urls.updateAppVideoById;
        }
        if (stopUpload) {
            stopSelf();
            return;
        }
        MyHttpRequest.postRequest(url, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    if (stopUpload) {
                        stopSelf();
                        return;
                    }
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        EventBus.getDefault().post(new MyEvent("RefreshVideo"));
                        MyToast.show("视频发布成功");
                        FileUtilss.delFile(uploadEntity.getVideo().getVideocompress());
                        if(!uploadEntity.getVideo().getFileUrl().equals(uploadEntity.getVideo().getVideocompress())){
                            FileUtilss.delFile(uploadEntity.getVideo().getFileUrl());
                        }
                        FileUtilss.delFile(uploadEntity.getVideo().getVideoCoverPath());
                        XJson.deleteUploadEntity(UploadVedioService.this, uploadEntity, UploadEntity.class);
                        Intent intent = new Intent();
                        intent.setPackage(getPackageName());
                        intent.setAction(MyUploadRecordActivity.videoTag);
                        intent.putExtra("tag", uploadEntity.getUploadTag());
                        intent.putExtra("percent", 100);
                        LocalBroadcastManager.getInstance(UploadVedioService.this).sendBroadcast(intent);
                        EventBus.getDefault().post(new MyEvent("refreshUploadRecord"));
                        stopSelf();

                    } else {
                        deleteId(uploadEntity.getVideo().getVideoId());
                        EventBus.getDefault().post(new MyEvent("Stop_File_Upload"));
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                        stopSelf();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    deleteId(uploadEntity.getVideo().getVideoId());
                    EventBus.getDefault().post(new MyEvent("Stop_File_Upload"));
                    stopSelf();
                    MyToast.show("视频发布失败，请稍后重试");
                }

            }
        });
    }

    private void deleteId(String videoId) {
        Map<String, String> map = new HashMap<>();
        map.put("videoId", videoId);
        MyHttpRequest.postRequest(Urls.deleteVideoByVideoId, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                stopSelf();
            }
        });
    }

    private NotificationManager mNManager;
    private Notification notification;

    private void initNotification() {
        //获得通知消息管理类对象
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Bitmap largeBitmap = GlideUtils.loadLogo(this);
        notification = new Notification(GlideUtils.loadLogoId(this), "带进条的提醒", System.currentTimeMillis());
//Android8.0以上必须添加 渠道 才能显示通知栏
        RemoteViews contentView = new RemoteViews(getApplication().getPackageName(), R.layout.vedio_upload);
        contentView.setProgressBar(R.id.progressbarUpload, 100, 0, false);
        contentView.setTextViewText(R.id.tvProcess, "已上传" + "0%");
        contentView.setImageViewResource(R.id.appdown_ivLogo, GlideUtils.loadLogoId(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建渠道
            String id = "vedio_upload_channel";
            String name = getResources().getString(R.string.app_name);
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            mNManager.createNotificationChannel(mChannel);
            //设置图片,通知标题,发送时间,提示方式等属性
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
            int PROGRESS_MAX = 100;
            int PROGRESS_CURRENT = 0;
            builder.setCustomContentView(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
//            startForeground(1, notification);

        } else {
            //设置图片,通知标题,发送时间,提示方式等属性
            Notification.Builder builder = new Notification.Builder(this);
            builder.setContent(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        }
        mNManager.notify(NotificationId, notification);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            notification.contentView.setProgressBar(R.id.progressbarUpload, 100, msg.arg1,
                    false);
            notification.contentView.setTextViewText(R.id.tvProcess, "已上传"
                    + msg.arg1 + "%");
            mNManager.notify(NotificationId, notification);
            if (msg.arg1 == 100) {
                mNManager.cancel(NotificationId);
            }
            super.handleMessage(msg);
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("Stop_File_Upload")) {
                //中止上传任务
                stopUpload = true;
                if (vodsVideoUploadClient != null) {
                    vodsVideoUploadClient.pause();
                    vodsVideoUploadClient.cancel();
                    stopSelf();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        KLog.i("jaa", "中止视频上传");
        if (vodsVideoUploadClient != null) {
            vodsVideoUploadClient.cancel();
        }
        if (mNManager != null) {
            mNManager.cancel(NotificationId);
        }
    }
}